import React, { useState, useEffect } from 'react';
import { Card, Typography, Space, Table, Tag, Button, Row, Col, Statistic, DatePicker, Input, Select, Spin, Empty, message } from 'antd';
import { ShoppingOutlined, ClockCircleOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { getUserOrders, payOrder, cancelOrder } from '../api/divide/order/sdk.gen';
import type { OrderVo } from '../api/divide/order/types.gen';
import { EyeOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Search } = Input;

const Orders: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [searchText, setSearchText] = useState('');
  const [dateRange, setDateRange] = useState<any>(null);
  const [orders, setOrders] = useState<OrderVo[]>([]);
  const [loading, setLoading] = useState(false);
  const [payingOrderId, setPayingOrderId] = useState<number | null>(null);
  const [cancellingOrderId, setCancellingOrderId] = useState<number | null>(null);
  
  const navigate = useNavigate();
  
  // 订单状态映射 - 现在直接使用字符串状态
  const statusMap = {
    '待支付': { text: '待支付', color: 'orange', icon: <ClockCircleOutlined /> },
    '已支付': { text: '已支付', color: 'blue', icon: <ShoppingOutlined /> },
    '已完成': { text: '已完成', color: 'green', icon: <CheckCircleOutlined /> },
    '已取消': { text: '已取消', color: 'red', icon: <CloseCircleOutlined /> },
    '已退款': { text: '已退款', color: 'purple', icon: <CloseCircleOutlined /> },
  };
  
  // 获取状态信息的安全函数 - 适配字符串状态
  const getStatusInfo = (status: string | undefined) => {
    const defaultStatus = { text: '未知', color: 'default', icon: <ClockCircleOutlined /> };
    return status ? statusMap[status as keyof typeof statusMap] || defaultStatus : defaultStatus;
  };

  // 状态过滤
    const [statusFilter, setStatusFilter] = useState<string>('all');
  
  // 过滤订单
  const filteredOrders = orders.filter(order => {
    const matchesSearch = searchText === '' || 
      order.orderNo?.toLowerCase().includes(searchText.toLowerCase()) ||
      order.courseTitle?.toLowerCase().includes(searchText.toLowerCase());
    
    const matchesDate = !dateRange || !order.createTime || (
      new Date(order.createTime) >= dateRange[0].toDate() &&
      new Date(order.createTime) <= dateRange[1].toDate()
    );
  
    const matchesStatus = statusFilter === 'all' || order.status === statusFilter;
    
    return matchesSearch && matchesDate && matchesStatus;
  });
  
  // 状态选项 - 使用字符串状态值
  const statusOptions = [
    { label: '全部', value: 'all' },
    { label: '待支付', value: '待支付' },
    { label: '已支付', value: '已支付' },
    { label: '已完成', value: '已完成' },
    { label: '已取消', value: '已取消' },
    { label: '已退款', value: '已退款' },
  ];

  // 状态统计 - 使用字符串状态值


  // 获取订单列表
  const fetchOrders = async () => {
    setLoading(true);
    try {
      const response = await getUserOrders();
      if (response.data?.code === 200 && response.data.data) {
        setOrders(response.data.data);
      } else {
        message.error('获取订单列表失败');
      }
    } catch (error) {
      console.error('获取订单失败:', error);
      message.error('获取订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrders();
  }, []);

  // 处理支付
  const handlePay = async (orderId: number) => {
    setPayingOrderId(orderId);
    try {
      const response = await payOrder({
        body: { orderId, paymentMethod: 1 }
      });
      if (response.data?.code === 200) {
        message.success('支付成功');
        fetchOrders(); // 重新获取订单列表
      } else {
        message.error(response.data?.message || '支付失败');
      }
    } catch (error) {
      console.error('支付失败:', error);
      message.error('支付失败');
    } finally {
      setPayingOrderId(null);
    }
  };

  // 处理取消订单
  const handleCancel = async (orderId: number) => {
    setCancellingOrderId(orderId);
    try {
      const response = await cancelOrder({
        body: { orderId }
      });
      if (response.data?.code === 200) {
        message.success('取消订单成功');
        fetchOrders(); // 重新获取订单列表
      } else {
        message.error(response.data?.message || '取消订单失败');
      }
    } catch (error) {
      console.error('取消订单失败:', error);
      message.error('取消订单失败');
    } finally {
      setCancellingOrderId(null);
    }
  };

  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 200,
    },
    {
      title: '课程名称',
      dataIndex: 'courseTitle',
      key: 'courseTitle',
      ellipsis: true,
    },
    {
      title: '价格',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount: number) => (
        <span style={{ color: '#ff4d4f', fontWeight: 'bold' }}>
          ¥{amount}
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusInfo = getStatusInfo(status);
        return (
          <Tag color={statusInfo.color} icon={statusInfo.icon}>
            {statusInfo.text}
          </Tag>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (date: string) => new Date(date).toLocaleDateString('zh-CN'),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record: OrderVo) => (
        <Space>
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => navigate(`/orders/${record.orderId}`)}
          >
            查看详情
          </Button>
          {record.status === '待支付' && (
            <>
              <Button 
                type="primary" 
                size="small"
                loading={payingOrderId === record.orderId}
                onClick={() => handlePay(record.orderId!)}
              >
                付款
              </Button>
              <Button 
                size="small" 
                danger
                loading={cancellingOrderId === record.orderId}
                onClick={() => handleCancel(record.orderId!)}
              >
                取消
              </Button>
            </>
          )}
          {record.status === '已支付' && (
            <Button size="small" type="primary">
              查看课程
            </Button>
          )}
          {record.status === '已完成' && (
            <Button size="small" type="primary">
              继续学习
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const stats = {
    total: filteredOrders.length,
    pending: filteredOrders.filter(o => o.status === '待支付').length,
    paid: filteredOrders.filter(o => o.status === '已支付').length,
    completed: filteredOrders.filter(o => o.status === '已完成').length,
    cancelled: filteredOrders.filter(o => o.status === '已取消').length,
    refunded: filteredOrders.filter(o => o.status === '已退款').length,
  };

  return (
    <div style={{ padding: '24px' }}>
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        <Title level={2}>订单管理</Title>
        
        {/* 统计卡片 */}
        <Row gutter={16}>
          <Col span={4}>
            <Card>
              <Statistic
                title="总订单数"
                value={stats.total}
                prefix={<ShoppingOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="待付款"
                value={stats.pending}
                valueStyle={{ color: '#faad14' }}
                prefix={<ClockCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="已付款"
                value={stats.paid}
                valueStyle={{ color: '#1890ff' }}
                prefix={<ShoppingOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="已完成"
                value={stats.completed}
                valueStyle={{ color: '#3f8600' }}
                prefix={<CheckCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="已取消"
                value={stats.cancelled}
                valueStyle={{ color: '#ff4d4f' }}
                prefix={<CloseCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="已退款"
                value={stats.refunded}
                valueStyle={{ color: '#722ed1' }}
                prefix={<CloseCircleOutlined />}
              />
            </Card>
          </Col>
        </Row>

        {/* 搜索和筛选 */}
        <Card>
          <Row gutter={16} align="middle">
            <Col span={6}>
              <Search 
                placeholder="搜索订单号或课程" 
                allowClear 
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
              />
            </Col>
            <Col span={6}>
              <Select
                style={{ width: '100%' }}
                placeholder="选择订单状态"
                value={statusFilter}
                onChange={setStatusFilter}
                options={statusOptions}
              />
            </Col>
            <Col span={6}>
              <RangePicker 
                style={{ width: '100%' }}
                value={dateRange}
                onChange={setDateRange}
              />
            </Col>
            <Col span={6}>
              <Button type="primary" onClick={() => fetchOrders()}>
                刷新
              </Button>
            </Col>
          </Row>
        </Card>

        {/* 订单列表 */}
        <Card>
          <Table
            rowSelection={rowSelection}
            columns={columns}
            dataSource={filteredOrders}
            rowKey="orderId"
            loading={loading}
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
            }}
            locale={{
              emptyText: <Empty description="暂无订单数据" />,
            }}
          />
        </Card>
      </Space>
    </div>
  );
};

export default Orders;